<template>
  <div class="login">
    <div class="login_logo"></div>
    <div class="login_main">
      <div class="left_banner"></div>
      <div class="right_form">
        <div class="form_title"></div>
        <el-form ref="loginForm" auto-complete="on" :model="loginForm" :rules="loginRules" class="login-form"
          label-position="left">
          <div class="title-container">
            <h3 class="title"></h3>
          </div>
          <el-form-item prop="userName">
            <span class="svg-container">
              <i class="el-icon-user" style="font-size: 20px;"></i>
            </span>
            <el-input ref="userName" v-model="loginForm.userName" placeholder="用户名" name="userName" type="text"
              tabindex="1" />
          </el-form-item>
          <el-form-item prop="password">
            <span class="svg-container">
              <i class="el-icon-unlock" style="font-size: 20px;"></i>
            </span>
            <el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType"
              placeholder="密码" name="password" tabindex="2" @keyup.enter.native="handleLogin" />
            <span class="show-pwd" @click="showPwd">
              <i :class="passwordType === 'password' ? 'el-icon-minus' : 'el-icon-view'
                "></i>
            </span>
          </el-form-item>
          <el-button :loading="loading" type="primary" style="width:100%;background: linear-gradient(90deg, #4591EF, #3D6BFC);
border-radius: 6px;" @click.native.prevent="handleLogin">登录</el-button>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { getUserInfo } from "@/api/user.js";
import { getMenuTreeByRoles, getOrgDepartmentName } from "@/api/common.js";
import { getMenuTreeByRole } from "@/api/SystemConfig/menuConfig.js";
import axios from "@/api/index";
import JSEncrypt from "jsencrypt";
export default {
  components: {},
  data() {
    return {
      loginForm: {
        userName: "",
        password: "",
        loginType: "app"
      },
      receiveMessage: {},
      loginRules: {
        userName: [
          { required: true, trigger: "blur", message: "请输入用户名" }
        ],
        password: [{ required: true, trigger: "blur", message: "请输入密码" }]
      },
      loading: false,
      passwordType: "password",
      redirect: undefined

    };
  },
  computed: {},
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  methods: {
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    webSocketInit() {
      const FilledBy = {
        accessToken: JSON.parse(sessionStorage.getItem("accessToken")), // token
        unsrId: JSON.parse(sessionStorage.getItem("account")).id
      };
      const Url = "ws://192.168.0.206:16070/system/websocket/" + FilledBy.unsrId;
      const Url1 = "wss://192.168.0.206:16070/system/websocket/" + FilledBy.unsrId;
      const webSocketUrl = process.env.NODE_ENV === "test" ? Url1 : Url;
      this.webSocketObject = new WebSocket(webSocketUrl);
      this.webSocketObject.onopen = this.webSocketOnOpen;
      this.webSocketObject.onmessage = this.webSocketOnMessage;
      this.webSocketObject.onerror = this.webSocketOnError;
      this.webSocketObject.onclose = this.webSocketOnClose;
    },
    webSocketOnOpen(e) {
      console.log("与服务端连接打开login", e);
    },
    webSocketOnMessage(e) {
      console.log("来自服务端的消息app", e);
      this.receiveMessage = JSON.parse(e.data);
      this.$store.commit("SET_MessageCount", this.receiveMessage.msgNum);
      this.openMessage(this.receiveMessage);
    },
    websocketsend(agentData) {
      // 数据发送
      this.websock.send(agentData);
    },
    webSocketOnError(e) {
      console.log("与服务端连接异常->", e);
    },
    webSocketOnClose(e) {
      console.log("与服务端连接关闭->", e);
    },
    openMessage(val) {
      if (val.approveState === "0") {
        const h = this.$createElement;
        this.$notify({
          title: "你有新的代办事项！",
          dangerouslyUseHTMLString: true,
          // showClose: false,
          message: h("p", null, [
            h("span", {
              class: "details", on: {
                click: () => { this.clickBtnDetails(val); }
              }
            }, "详情>"),
            h("p", null, '"' + this.receiveMessage.title + '"' + this.receiveMessage.approveStateName + "！"),
            h("p", null, "提交人：" + this.receiveMessage.submitUserName),
            h("p", null, "提交时间：" + this.receiveMessage.formatTime),
            h("span", {
              class: "daiban",
              on: {
                click: () => { this.clickBtnAgree(); }
              }
            }, "同意"),
            h("span", {
              class: "bohui",
              on: {
                click: () => { this.clickBtnReject(); }
              }
            }, "驳回"),
            h("span", {
              class: "zanbuchuli",
              on: {
                click: () => { this.clickBtnNotProcessedTemporarily(); }
              }
            }, "暂不处理")
          ]),
          duration: 0
        });
      } else if (val.approveState === "1") {
        const h = this.$createElement;
        this.$notify({
          title: "你有新的代办事项！",
          dangerouslyUseHTMLString: true,
          // showClose: false,
          message: h("p", null, [
            h("span", {
              class: "details", on: {
                click: () => { this.clickBtnDetails(val); }
              }
            }, "详情>"),
            h("p", null, '"' + this.receiveMessage.title + '"' + this.receiveMessage.approveStateName + "！"),
            h("p", null, "发布人：" + this.receiveMessage.issueUserName),
            h("p", null, "发布时间：" + this.receiveMessage.formatTime)
          ]),
          duration: 0
        });
      }
    },
    // 详情
    clickBtnDetails(val) {
      this.$router.push({ path: val.route });
      this.$notify.closeAll();
    },
    // 同意
    clickBtnAgree() {
      const addForm = {
        approveSign: "pass",
        id: this.receiveMessage.formId
      };
      axios.request({
        url: `${this.receiveMessage.requestUrl}`,
        method: "post",
        data: addForm
      }).then(res => {
        if (res) {
          this.$notify.closeAll();
        }
      });
    },
    // 驳回
    clickBtnReject() {
      console.log("驳回");
      const addForm = {
        approveSign: "reject",
        id: this.receiveMessage.formId
      };
      axios.request({
        url: `${this.receiveMessage.requestUrl}`,
        method: "post",
        data: addForm
      }).then(res => {
        if (res) {
          this.$notify.closeAll();
        }
      });
    },
    // 暂不处理
    clickBtnNotProcessedTemporarily() {
      this.$notify.closeAll();
    },
    encryptSingle(value) {
      const publicKey =
        "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQdPn6+Dy0m7fpsvqF/79Uhmo2HneV1Ee40Bx2rk8FtocEz6YxbSr4I4k2WKEr+7Zker9jYgjJMISF3lmH5wnGealTbp1ADSTzto8dLhMYogxfhnJSbk5TjYPFtNDOE7JMMpaW9ZhOkknozfUgZ+s9mVsecUosN31dUimN3D+woQIDAQAB";
      if (value) {
        const encrypt = new JSEncrypt();
        encrypt.setPublicKey(publicKey);
        return encrypt.encrypt(value);
      } else {
        return "";
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          await getUserInfo({
            userName: this.loginForm.userName,
            password: this.encryptSingle(this.loginForm.password),
            loginType: "app"
          }).then(async (res) => {
            console.log(res, "登录信息");
            if (res) {
              await getMenuTreeByRole(res.roleId).then(menuConfig => {
                const org = {
                  orgCode: res.orgId,
                  // orgCode: res.orgCode,
                  orgId: res.orgId,
                  orgName: res.orgName,
                  departmentName: res.superiorDept,
                  unitName: res.unitName,
                  level: Number(res.level),
                  superiorDeptId: res.superiorDeptId,
                  superiorDept: res.superiorDept,
                  ssbmId: res.ssbmId,
                  ssbmName: res.ssbmName
                };
                getOrgDepartmentName(org.orgId).then(dwbm => {
                  let dwbmName = "";
                  if (dwbm.includes("/")) {
                    const arr = dwbm.split("/");
                    dwbmName = arr.join("");
                  } else {
                    dwbmName = dwbm;
                  }
                  sessionStorage.setItem("dwbmName", dwbmName);
                });
                const role = {
                  roleCode: res.roleCode,
                  roleId: res.roleId,
                  roleName: res.roleName
                };
                const account = {
                  id: res.id,
                  realName: res.realName
                };
                sessionStorage.setItem("org", JSON.stringify(org));
                sessionStorage.setItem("role", JSON.stringify(role));
                sessionStorage.setItem("account", JSON.stringify(account));
                sessionStorage.setItem("accessToken", JSON.stringify(res.accessToken));
                this.$store.commit("SET_MenuIndex", 1);
                if (menuConfig.length > 0) {
                  // 去掉系统配置菜单下的子模块内容
                  let result = menuConfig.map(i => {
                    if (i.menuName === "系统配置") {
                      i.children = [];
                    }
                    return i;
                  });
                  result = result.filter(item => item.menuName !== "APP端");
                  this.$store.commit("SET_MenuTree", result);
                  this.$message({
                    message: "登录成功",
                    type: "success"
                  });
                  console.log(result[0].menuUrl, "----result[0].menuUrl");
                  this.$router.push({ path: result[0].menuUrl });
                  if (result[0].parent && result[0].parent != "1480016250535968") {
                    this.$store.commit("SET_MenuIndex", result[0].parent);
                  } else {
                    this.$store.commit("SET_MenuIndex", result[0].id);
                  }
                  this.webSocketInit();
                  this.loading = false;
                } else {
                  this.$message({
                    message: "当前账号角色没有菜单权限，请先配置菜单",
                    type: "warning"
                  });
                  sessionStorage.clear();
                  this.loading = false;
                }
              });
            } else {
              this.loading = false;
            }
          }).catch(() => {
            this.loading = false;
          });
          // 获取当前角色按钮权限
          const roleId = JSON.parse(sessionStorage.getItem("role")).roleId;
          await getMenuTreeByRoles(roleId).then(power => {
            if (power) {
              this.$store.commit("SET_Power", power);
            }
          });
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style lang='less' scoped>
//@import url(); 引入公共css类
.login {
  width: 100%;
  height: 100%;
  background-image: url("../assets/img/login_bg.png");
  background-size: 100% 100%;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;

  .login_logo {
    width: 320px;
    height: 81px;
    background-image: url("../assets/img/dw_logo.png");
    background-size: 100% 100%;
    position: absolute;
    top: 20px;
    left: 35px;
  }

  .login_main {
    width: 1494.8px;
    height: 690px;
    background-color: #f3f5f7;
    border-radius: 8px;
    display: flex;
    align-items: center;

    // padding: 30px 90px;
    .left_banner {
      width: 48%;
      height: 550px;
      margin-left: 60px;
      margin-top: 7px;
      background-image: url("../assets/img/login_banner.png");
      background-size: 100% 100%;
    }

    .right_form {
      width: 40%;
      margin-right: 60px;
      display: flex;
      flex-direction: column;

      .el-input {
        display: inline-block;
        height: 47px;
        width: 85%;
        outline: none;

        input {
          background: transparent;
          border: 0px;
          padding: 12px 5px 12px 15px;
          color: #fff;
          height: 47px;
          caret-color: #fff;

          // &:-webkit-autofill {
          //   box-shadow: 0 0 0px 1000px #283443 inset !important;
          //   -webkit-text-fill-color: #fff !important;
          // }
        }

        :deep(.el-input__inner) {
          border: none;
          outline: none;
          background-color: #fff;
        }
      }

      .login-form {
        position: relative;
        width: 100%;
        max-width: 100%;
        padding: 60px 0 0 0;
        margin: 0 auto;
        overflow: hidden;
      }

      .svg-container {
        padding: 6px 5px 7px 15px;
        // color: #889aa4;
        vertical-align: middle;
        width: 30px;
        display: inline-block;
        color: #378dfd;
      }

      .el-form-item {
        border: 1px solid rgba(255, 255, 255, 0.1);
        background: #fff;
        border-radius: 5px;
        color: #454545;
      }

      .form_title {
        height: 107px;
        background-image: url("../assets/img/login_title.png");
        background-size: 100% 100%;
      }
    }
  }
}

:deep(.el-input__inner) {
  background-color: rgba(255, 255, 255, 0) !important;
  height: 55px !important;
  font-size: 20px !important;
  color: #333333;
}

// :deep(.el-input) {
.el-input {
  input {
    -webkit-appearance: none;

  }
}

:deep(.el-input__inner:-webkit-autofill) {
  transition: background-color 5000s ease-in-out 0s;
  font-size: 20px !important;
  color: #333333;
}

:deep(.el-input__inner:-webkit-autofill:focus) {
  -webkit-text-fill-color: #333 !important;
  font-size: 20px !important;
  color: #333333;
}

:deep(.el-button) {
  height: 55px !important;
  font-size: 20px !important;
}
</style>
